<template>

  <div class="filter-container">

    <el-form
      :inline="true"
      :model="formData"
      class="filter-form-inline"
      label-position="right"
      size="small"
    >
      <el-row
        :gutter="20"
        style="margin-left: 0px; margin-right: 0px"
      >
        <!--
        <el-col :span="6">
          <el-form-item
            label="状态"
            style="width: 100%"
          >
            <el-select
              v-model="formData.status"
              clearable
              style="width: 100%"
              placeholder="请选择状态"
              @change="listSearch"
            >
              <el-option
                v-for="item in statusOption"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        -->
        <el-col :span="6">
          <el-form-item
            label="产品信息"
            style="width: 100%"
          >
            <el-select
              v-model="formData.productId"
              style="width: 100%"
              :loading="loading"
              :remote-method="remoteMethod"
              clearable
              filterable
              placeholder="请选择产品"
              remote
              reserve-keyword
              @change="productChange"
            >
              <el-option
                v-for="item in products"
                :key="item.id"
                :label="item.productPopularName"
                :value="item.id"
              >
                {{ item.name }}
              </el-option>
            </el-select>

          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item
            label="终端所在地区"
            style="width: 100%"
          >
            <el-cascader
              v-model="formData.area"
              :show-all-levels="false"
              style="width: 100%;"
              :options="citys"
              placeholder="请选择终端所在地区"
              :props="{ checkStrictly : true, expandTrigger: 'hover', label: 'regionName', value:'regionCode' }"
              @change="listSearch"
            />
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item
            label="终端名称"
            style="width: 100%"
          >
            <el-input
              v-model="formData.keyWord"
              clearable
              placeholder="输入终端名称"
            />
          </el-form-item>
        </el-col>

        <el-col :span="6">
          <el-form-item style="width: 100%">
            <el-button
              class="border-btn"
              @click="reset"
            >重置
            </el-button>
            <el-button
              class="main-btn"
              type="primary"
              @click="listSearch"
            >搜索
            </el-button>
          </el-form-item>
        </el-col>

      </el-row>
    </el-form>

  </div>

  <table-view
    :data="tableData"
    :visible="visible"
    @row-click="rowClick"
  >
    <el-table-column
      :min-width="140"
      align="left"
      header-align="center"
      label="编号"
      prop="planDetail.detailNo"
      fixed="left"
      show-overflow-tooltip
    />
    <el-table-column
      :min-width="150"
      fixed="left"
      header-align="center"
      label="终端名称"
      prop="planDetail.terminalName"
      show-overflow-tooltip
    />
    <el-table-column
      :min-width="120"
      header-align="center"
      label="终端所在地区"
      prop="agentName"
      show-overflow-tooltip
    >
      <template #default="scope">
        {{ scope.row.planDetail?.terProvinceName }}/{{
          scope.row.planDetail?.terCityName
        }}/{{ scope.row.planDetail?.terAreaName }}
      </template>
    </el-table-column>
    <el-table-column
      :min-width="100"
      header-align="center"
      label="通用名"
      prop="planInfo.productPopularName"
      show-overflow-tooltip
    />
    <el-table-column
      :min-width="100"
      header-align="center"
      label="商品名"
      prop="planInfo.productName"
      show-overflow-tooltip
    />
    <el-table-column
      :min-width="100"
      header-align="center"
      label="包装规格"
      prop="planInfo.packSpecs"
      show-overflow-tooltip
    />
    <el-table-column
      :min-width="100"
      header-align="center"
      label="生产厂家"
      prop="planInfo.producer"
      show-overflow-tooltip
    />
    <el-table-column
      :min-width="100"
      align="center"
      header-align="center"
      label="准入模式"
    >
      <template #default="scope">
        {{ getLabel('access_mode', scope.row.planInfo?.accessMode) }}
      </template>
    </el-table-column>
    <!--
    <el-table-column
      :min-width="100"
      align="center"
      header-align="center"
      label="终端价(元)"
      prop="planInfo.terminalPrice"
    />
    <el-table-column
      :min-width="100"
      align="center"
      header-align="center"
      label="营销体量"
    >
      <template #default="scope">
        {{ getLabel('sales_volume', scope.row.planDetail.salesVolume) }}
      </template>
    </el-table-column>
    <el-table-column
      :min-width="140"
      align="center"
      header-align="center"
      label="开发期限截至"
    >
      <template #default="scope">
        {{ dateFormat('yyyy-mm-dd', scope.row.planDetail.expireTime) }}
      </template>
    </el-table-column>
    <el-table-column
      align="center"
      header-align="center"
      label="开发保证金(元)"
      prop="address"
      :min-width="150"
    >
      <template #default="scope">
        <span v-if="scope.row.planDetail?.devEarnestMoney">{{ scope.row.planDetail?.devEarnestMoney }}</span>
        <span v-else>未设置</span>
      </template>
    </el-table-column>
    <el-table-column
      align="center"
      header-align="center"
      label="最低销量"
      min-width="150px"
      prop="address"
    >
      <template #default="scope">

        <span v-if="scope.row.planDetail?.minSale">{{
          scope.row.planDetail?.minSale
        }}{{
          getLabel('sell_unit', scope.row.planInfo?.sellUnit)
        }}/{{ getLabel('sell_num_unit', scope.row.planDetail?.minSaleUnit) }}</span>
        <span v-else>未设置</span>
      </template>
    </el-table-column>
    <el-table-column
      align="center"
      header-align="center"
      label="销量保证金(元)"
      :min-width="150"
    >
      <template #default="scope">

        <span v-if="scope.row.planDetail?.sellEarnestMoney">{{ scope.row.planDetail?.sellEarnestMoney }}</span>
        <span v-else>未设置</span>
      </template>
    </el-table-column>
    <el-table-column
      align="center"
      header-align="center"
      label="跟进职员"
      prop="planDetail.headName"
    />
    <el-table-column
      :min-width="150"
      align="center"
      fixed="right"
      header-align="center"
      label="状态"
    >
      <template #default="scope">
        {{ getStatus(scope.row) }}
      </template>
    </el-table-column>
    -->
    <el-table-column
      :min-width="140"
      align="center"
      header-align="center"
      label="发布时间"
    >
      <template #default="scope">
        <span v-if="scope.row.planInfo?.putTime">{{ dateFormat('yyyy-mm-dd HH:MM', scope.row.planInfo.putTime) }}</span>
        <span v-else>无</span>
      </template>
    </el-table-column>
    <el-table-column
      :min-width="220"
      align="center"
      fixed="right"
      header-align="center"
      label="操作"
    >
      <template #default="{row}">
        <el-button
          type="text"
          @click.stop="onEditorial(row)"
        >推荐代理
        </el-button>
        <el-button
                v-auth="{v:['crm:planFinePublicity:pms'],bool:row.planDetail?.detailStatus != 4}"
                type="text"
                @click.stop="endClick(row)"
        >结束
        </el-button>
<!--        <el-button-->
<!--          v-auth="{v:['crm:planFinePublicity:pms'],bool:row.planDetail?.detailStatus == 1}"-->
<!--          type="text"-->
<!--          @click.stop="resultClick(row)"-->
<!--        >代理开发失败-->
<!--        </el-button>-->
<!--        <el-button-->
<!--          v-auth="{v:['crm:planFinePublicity:pms'],bool:row.planDetail?.detailStatus > 1 && row.planDetail?.detailStatus != 4}"-->
<!--          type="text"-->
<!--          @click.stop="failClick(row)"-->
<!--        >终端开发失败-->
<!--        </el-button>-->
      </template>
    </el-table-column>
  </table-view>

  <Pagination
    v-model:limit="formData.pageSize"
    v-model:page="formData.page"
    :total="total"
    style="display: flex; justify-content: flex-end"
    @pagination="getList"
  />

  <resultDialog
    ref="resultDialog"
    @success="getList"
  />

</template>

<script>
import { useRouter } from 'vue-router'
import {
  defineAsyncComponent,
  defineComponent,
  getCurrentInstance,
  inject,
  onMounted,
  reactive,
  toRefs,
  ref,
} from 'vue'
import area from '../../../../../../../utils/area'

export default defineComponent({
  name: 'FineList',
  components: {
    resultDialog: defineAsyncComponent(() =>
      import('../../modules/resultDialog.vue')
    ),
  },
  setup(props, {}) {
    const router = useRouter()
    const currentInstance = getCurrentInstance()
    const api = inject('api')
    const citys = area
    const statusOption = ref([
      {
        label: '待分配',
        value: '1',
      },
      {
        label: '代理开发中',
        value: '5',
      },
      {
        label: '终端开发中',
        value: '6',
      },
    ])
    var data = reactive({
      loading: false,
      products: [],
      tableData: [],
      formData: {
        listType: '2',
        page: 1,
        pageSize: 20,
        keyWord: '',
        planType: '1',
        detailStatus: '',
        region: [],
        allocationUserId: 0,
        productId: undefined,
        productName: '',
        state: '',
        area: [],
      },
      total: 0,
      visible: false,
      resultDialog: null,
    })

    const getList = () => {
      const a = { ...data.formData }
      if (a.area.length) {
        if (a.area.length == 1) {
          a.provinceCode = a.area[0]
        } else if (a.area.length == 2) {
          a.cityCode = a.area[1]
        } else if (a.area.length == 3) {
          a.areaCode = a.area[2]
        }
      }
      api.plan.PLAN_DETAIL_LIST(a).then((res) => {
        if (!res.code) {
          data.total = res.data.total
          data.tableData = res.data.list
        } else {
          currentInstance.proxy.customMessage({
            type: 'error',
            message: res.msg,
          })
        }
      })
    }

    const rowClick = (row) => {
      router.push({
        name: 'publicityDetail1',
        query: { id: row.planDetail.id },
      })
    }

    const resultClick = (row) => {
      currentInstance.proxy
        .alertBox({
          message: '确定更改此规划为开发失败？',
          title: '开发失败',
        })
        .then(() => {
          const d = {
            planDetailId: row.planDetail.id,
            result: '2',
          }
          api.plan.PLAN_AGENT_CONTRACT_RESULT(d).then((res) => {
            if (!res.code) {
              currentInstance.proxy.customMessage({
                type: 'success',
                message: '更新成功',
              })
              getList()
            } else {
              currentInstance.proxy.customMessage({
                type: 'error',
                message: res.msg,
              })
            }
          })
        })
        .catch((err) => {
          console.log(err)
        })
    }

    const failClick = (row) => {
      currentInstance.proxy
        .alertBox({
          message: '确定更改此规划为开发失败？',
          title: '开发失败',
        })
        .then(() => {
          api.terminal.TERMINAL_FAILURE(row.planDetail.devId).then((res) => {
            if (res.code) {
              currentInstance.proxy.customMessage({
                type: 'error',
                message: res.msg,
              })
            } else {
              currentInstance.proxy.customMessage({
                type: 'success',
                message: '操作成功',
              })
              getList()
            }
          })
        })
        .catch((err) => {
          console.log(err)
        })
    }

    const endClick = (row) => {
      currentInstance.proxy
              .alertBox({
                message: '确定更改此规划为结束？',
                title: '结束',
              })
              .then(() => {
                api.plan.PLAN_DO_END(row.planDetail.id).then((res) => {
                  if (!res.code) {
                    currentInstance.proxy.customMessage({
                      type: 'success',
                      message: '更新成功',
                    })
                    getList()
                  } else {
                    currentInstance.proxy.customMessage({
                      type: 'error',
                      message: res.msg,
                    })
                  }
                })
              })
              .catch((err) => {
                console.log(err)
              })
    }

    const onEditorial = (row) => {
      router.push({
        path: '/editorial/advanceAgent/create',
        query: { id: row.planDetail.id },
      })
    }

    const reset = () => {
      data.formData = {
        listType: '2',
        page: 1,
        pageSize: 20,
        keyWord: '',
        planType: '1',
        detailStatus: '',
        region: [],
        allocationUserId: 0,
        productId: undefined,
        productName: '',
        state: '',
        area: [],
      }
      listSearch()
    }

    const listSearch = () => {
      data.formData.page = 1
      getList()
    }

    const getStatus = (row) => {
      let str = ''

      switch (row.planDetail?.detailStatus) {
        case '0':
          str = '待分配'
          break
        case '-2':
          str = '待分配'
          break
        case '-3':
          str = '待分配'
          break
        case '-4':
          str = '待分配'
          break
        case '-5':
          str = '待分配'
          break
        case '1':
          str = '代理开发中'
          break
        case '2':
          str = '终端开发中'
          break
        case '3':
          str = '终端开发中'
          break
      }

      return str
    }

    const remoteMethod = (query) => {
      data.products = []
      data.loading = true
      data.searchStr = query

      if (query) {
        const pam = {
          keyWord: query,
        }
        api.common.GET_PRODUCT_LIST(pam).then((res) => {
          if (!res.code && res.data) {
            res.data.list.forEach((a) => {
              a.name = currentInstance.proxy.getProductName(a)
            })
            data.products = res.data.list
          } else {
            currentInstance.proxy.customMessage({
              type: 'error',
              message: res.msg,
            })
          }
          data.loading = false
        })
      } else {
        data.loading = false
      }
    }

    const productChange = (val) => {
      if (!val) {
        data.formData.productId = undefined
      }
      data.formData.page = 1
      getList()
    }

    onMounted(() => {
      getList()
    })

    return {
      ...toRefs(data),
      statusOption,
      citys,

      getList,
      reset,
      listSearch,
      resultClick,
      rowClick,
      failClick,
      onEditorial,
      getStatus,
      remoteMethod,
      productChange,
      endClick,
    }
  },
})
</script>

<style scoped>
</style>
